﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TriageQueueSystem.InterfacesImplementation
{
    public static class RegisterInterface
    {
        /// <summary>
        /// GalaSoft.MvvmLight.Ioc.SimpleIoc容器自动注入
        /// </summary>
        /// <param name="IocManager"></param>
        /// <returns></returns>
        public static bool RegisterInterfaceHandle(object IocManager)
        {

            if (IocManager == null)
                return false;

            //当前正在执行的代码的程序集
            var types2Register = Assembly.GetExecutingAssembly()
                                            .GetTypes()
                                            .Where(type => !string.IsNullOrEmpty(type.Namespace))
                                            .Where(type => type.BaseType != null && !type.BaseType.IsGenericType &&
                                                //这里自定义了一个接口，方便筛选
                                                type.GetInterface(nameof(IInterfaceBase)) != null);


            if (types2Register != null && types2Register.Count() != 0)
            {
                var iocType = IocManager.GetType();
                //根据接口名字获取IocManager所实现的接口
                //var iocInterface = iocType.GetInterface("ISimpleIoc");
                //获取IocManager下所有的方法函数
                //var iocAllMethods = iocType.GetMethods();
                //var registerMethods = iocAllMethods.Where(s => s.Name == "Register");
                //var firstMethods = iocAllMethods.Where(s => s.Name == "Register").FirstOrDefault();

                //var tempMethods = registerMethods.Where(s => s.GetGenericArguments().Length == 1);
                //var o = tempMethods.Where(s => s.GetParameters().Length == 0);

                //获取该类型下的Register方法
                //这边只需要Void Register<TClass>()这个函数
                var oldMethods = iocType.GetMethods().Where(s => s.Name == "Register"
                                                              //泛型类型参数个数为1个
                                                              && s.GetGenericArguments().Length == 1
                                                              //输入参数为0个参数
                                                              && s.GetParameters().Length == 0).FirstOrDefault();

                foreach (var item in types2Register)
                {
                    //定义泛型类型参数
                    var needMethods = oldMethods.MakeGenericMethod(new Type[] { item });
                    //调用委托实现注入
                    needMethods.Invoke(IocManager, null);
                }
            }

            return true;
        }
    }
}
